package com.hanxiaozhang;

import com.hanxiaozhang.http.BaseHttpServer;
import com.hanxiaozhang.http.config.ApplicationContext;
import com.hanxiaozhang.http.config.ApplicationContextLoader;
import com.hanxiaozhang.http.config.Context;
import com.hanxiaozhang.http.netty.HttpRequestHandler;
import com.hanxiaozhang.http.util.StringUtil;
import com.hanxiaozhang.http.util.ResourceUtil;
import com.hanxiaozhang.http.util.YamlUtil;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 *
 * @author hanxiaozhang
 * @create 2022/1/30
 * @since 1.0.0
 */
public class HttpServer {

    private final static Logger logger = Logger.getLogger(HttpServer.class);

    public static void main(String[] args) {
        Context context = new Context();
        try {
            context = readConfig();
        } catch (Exception e) {
            logger.error("read hanxiaozhang.yml error, error info [{}]", e);
            return;
        }
        String path = getJarPath(context);
        logger.debug("jar path  is " + path);

        ApplicationContextLoader loader = new ApplicationContextLoader();
        ApplicationContext applicationContext = loader.load(path);
        context.put("handlerMapper", applicationContext.getMapper());

        BaseHttpServer server = new BaseHttpServer(new HttpRequestHandler());
        server.setConfig(context);
        server.start();
    }


    /**
     * 读取配置信息
     *
     * @return
     * @throws FileNotFoundException
     */
    private static Context readConfig() throws IOException {
        InputStream inputStream = ResourceUtil.getInputStream("hanxiaozhang.yml");
        Map map = YamlUtil.parse(inputStream, "hanxiaozhang");
        Context context = new Context();
        context.putAll(map);
        inputStream.close();
        return context;
    }


    /**
     * 获取jar地址
     *
     * @param context
     * @return
     */
    private static String getJarPath(Context context) {
        String rootPath = System.getProperty("user.dir");
        String projectInfo = context.getString("projectName", "http_server") + "-" + context.getString("version", "1.0-SNAPSHOT") + ".jar";
        String path1 = rootPath + "\\" + projectInfo;
        String path2 = rootPath + "\\target\\" + projectInfo;
        File file1 = new File(path1);
        if (file1.exists()) {
            return path1;
        }
        return path2;
    }


}
